package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.InsertException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.function.support.RouterFunctionMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    //订单金额的最大值处理
    @Autowired
    private ShoppingPriceMaxService  shoppingPriceMaxService;
    //微信支付util
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    //TODO 这里是为了处理微信支付还没有接上来的情况!!
    private Orders orders;
    private int DEFAULT = 1;

    //保护用户信息
    private List<Orders> MessageUtil(List<Orders> list){
        //TODO保护用户隐私，防止用户信息泄露
        list.forEach(order -> {
            order.setAddressBookId(null);
            order.setUserId(null);
            order.setCancelReason(null);
            order.setCancelTime(null);
            order.setDeliveryTime(null);
            order.setPhone(null);
            order.setUserName(null);
        });
    return list;}
    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        log.info("处理业务异常 购物车是否有东西 地址是否是正确的！");
        //判断地址是否正确！
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            //地址不存在！
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车里是否有东西!!并且是否是过期菜品!!
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getShoppingCartList(BaseContext.getCurrentId());
        if(shoppingCartList == null || shoppingCartList.isEmpty()){
            //购物车没有东西！
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        List<Long> dishIds = new ArrayList<>();
        List<Long> setMealIds = new ArrayList<>();
        shoppingCartList.forEach(shoppingCart -> {
            if(shoppingCart.getDishId() != null){
                //是菜品
                dishIds.add(shoppingCart.getDishId());
            }else{
                //是套餐
                setMealIds.add(shoppingCart.getSetmealId());
            }
        });
        if(dishIds.isEmpty() && setMealIds.isEmpty()){
            //购物车没有东西！
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        int count = 0;
        //判断购物车中有过期的数据!
        //TODO这里不能直接放进Mapper层不然Length为0Mapper层会报错 也可以更改Mapper层的sql语句
        if(!dishIds.isEmpty()){
            count += dishMapper.getStatusNamesByIds(dishIds,StatusConstant.ENABLE).size();
        }
        //TODO这里不能直接放进Mapper层不然Length为0Mapper层会报错 也可以更改Mapper层的sql语句
        if(!setMealIds.isEmpty()){
            count += setMealMapper.getStatusNamesByIds(setMealIds,StatusConstant.ENABLE).size();
        }
       if(count != shoppingCartList.size()){
           //有过期的菜品！
           throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_EXPIRED);
       }
        log.info("当前校验通过!");
        User user = userMapper.queryById(BaseContext.getCurrentId());
        //首先要向订单表中插入一条数据！
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());//订单时间
        orders.setPayStatus(Orders.UN_PAID);//未支付
        orders.setStatus(Orders.PENDING_PAYMENT);//待付款
        orders.setUserId(BaseContext.getCurrentId());//用户id
        orders.setNumber(UUID.randomUUID().toString());//订单号
        //根绝用户id查询用户信息！
        orders.setUserName(user.getName());//用户姓名
        orders.setPhone(user.getPhone());//用户手机号
        StringBuilder sb = new StringBuilder();
        sb.append(addressBook.getProvinceName())//省份
                .append(addressBook.getCityName())//城市
                .append(addressBook.getDistrictName())//区县
                .append("||")
                .append(addressBook.getDetail());//详细地址
        orders.setAddress(sb.toString());//地址
        orders.setConsignee(addressBook.getConsignee());//收货人
        //还要向订单明细表中插入多条数据！
        //TODO 这里是为了处理微信支付还没有接上来的情况!!
        this.orders = orders;

        log.info("向订单表中插入数据");
        if(orders.getTablewareNumber()==0){
            orders.setTablewareStatus(DEFAULT);
        }
        int insertResult = orderMapper.insert(orders);
        if(insertResult== StatusConstant.RETURN0){
            throw new InsertException(MessageConstant.INSERT_FAILED);
        }
        //向订单明细表中插入数据！
        log.info("向订单明细表中插入数据");
        List<OrderDetail>  orderDetailList = new ArrayList<>();
        shoppingCartList.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        int insertOrderDetail = orderDetailMapper.insertBatch(orderDetailList);
        if(insertOrderDetail == StatusConstant.RETURN0){
            throw new InsertException(MessageConstant.INSERT_FAILED);
        }
        log.info("计算当前订单的总金额!");
        BigDecimal price = shoppingPriceMaxService.Price(BaseContext.getCurrentId());
        //查询购物车物品数量
        int num = shoppingCartMapper.countShoppingCart(BaseContext.getCurrentId());
        //TODO 这里的6元是默认的配送费
        price = price.add(new BigDecimal(num)).add(new BigDecimal(6));
        //清空购物车
        log.info("清空用户购物车");
        shoppingCartMapper.cleanCart(BaseContext.getCurrentId());
        //封装VO返回结果！
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(price)
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        //TODO 这里是为了处理原先微信支付的！(黑马写的!!)
        //------------------------------------------------------------------------------------------------------------
        //当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.queryById(userId);
        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        //------------------------------------------------------------------------------------------------------------



        //TODO 博客写的(模拟支付成功！)！！！！
        //------------------------------------------------------------------------------------------------------------
        //模拟支付成功！
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        LocalDateTime check_out_time = LocalDateTime.now();//更新支付时间
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, this.orders.getId());

        //这里要通过websocket给后端服务传递订单信息 type orderId content
        //TODO WebSocket 提醒后端!!
        Map<String, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",this.orders.getId());
        map.put("content","订单号："+this.orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        log.info("来单啦！！！{}",JSON.toJSONString(map));
        //------------------------------------------------------------------------------------------------------------
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     * @param outTradeNo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //这里要通过websocket给后端服务传递订单信息 type orderId content
        //TODO WebSocket 提醒后端!!
        Map<String, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        log.info("来单啦！！！");
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageOrderQuery(OrdersPageQueryDTO ordersPageQueryDTO, String who) {
        //设置用户的id方便查询
        if(who.equals("admin")){
            ordersPageQueryDTO.setUserId(null);
        }else {
            ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        }
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> pageResult = orderMapper.pageOrderQuery(ordersPageQueryDTO);
        //获取分页查询的result结果
        List<Orders> result = pageResult.getResult();
        //获取所有订单的id
        List<Long> orderIds = result.stream().map(Orders::getId).collect(Collectors.toList());
        //通过当前的所有的订单id查询订单详细信息
        if(!orderIds.isEmpty()){
            List<OrderDetail> orderDetailList = orderDetailMapper.queryOrderDetailByOrderIds(orderIds);
            Map<Long, List<OrderDetail>> orderDetailMap = orderDetailList.stream().collect(Collectors.groupingBy(OrderDetail::getOrderId));
            result.forEach(order -> {
                order.setOrderDetailList(orderDetailMap.get(order.getId()));
            });
        }
        if(who.equals("admin")){
            return new PageResult(pageResult.getTotal(),result);
        }else {
            //TODO保护用户隐私，防止用户信息泄露
            result = MessageUtil(result);
            return new PageResult(pageResult.getTotal(),result);
        }

    }
    /**
     * 查询订单详细
     * @param id
     * @return
     */
    @Override
    public Orders getAllOrderDetail(Long id,String who) {
        Page<Orders> pageResult = orderMapper.pageOrderQuery(OrdersPageQueryDTO.builder().id(id).build());
        List<Orders> result = pageResult.getResult();
        List<OrderDetail> orderDetailsResult = orderDetailMapper.queryOrderDetailByOrderIds(result.stream().map(Orders::getId).collect(Collectors.toList()));
        result.forEach(order -> {
            order.setOrderDetailList(orderDetailsResult);
        });
        if(who.equals("admin")){
            return result.get(0);
        }else {
            return MessageUtil(result).get(0);
        }
    }

    /**
     * 取消订单
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelOrder(Long id) {

        // 根据id查询订单
        Page<Orders> page = orderMapper.pageOrderQuery(OrdersPageQueryDTO.builder().id(id).build());
        Orders ordersDB = page.getResult().get(0);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //TODO调用微信支付退款接口


            //------------------------------------------------------------------------------------------------------------
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            //------------------------------------------------------------------------------------------------------------



            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户自己取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    /**
     * Admin个个状态订单数量统计!
     * @return
     */
    @Override
    public OrderStatisticsVO orderStatistics() {
        List<Orders> list = orderMapper.countStatus();
        Map<Integer, List<Orders>> map = list.stream().collect(Collectors.groupingBy(Orders::getStatus));
        return OrderStatisticsVO.builder()
                .toBeConfirmed(map.get(Orders.TO_BE_CONFIRMED) == null ? 0 : map.get(Orders.TO_BE_CONFIRMED).size())
                .confirmed(map.get(Orders.CONFIRMED) == null ? 0 : map.get(Orders.CONFIRMED).size())
                .deliveryInProgress(map.get(Orders.DELIVERY_IN_PROGRESS) == null ? 0 : map.get(Orders.DELIVERY_IN_PROGRESS).size())
                .build();
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //跳过 weChatPayUtil.refund调用，模拟给用户退款，直接更新数据库订单支付状态为 ”已退款 “
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            log.info("给订单{}退款", ordersDB.getNumber());
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setPayStatus(Orders.REFUND);//修改订单支付状态为 ”已退款 “

        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("管理员拒单");
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }
    /**
     * 管理员取消订单
     * @param ordersCancelDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //跳过 weChatPayUtil.refund调用，模拟给用户退款，直接更新数据库订单支付状态为 ”已退款 “
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            log.info("给订单{}退款", ordersDB.getNumber());
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setPayStatus(Orders.REFUND);//修改订单支付状态为 ”已退款 “

        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     * @return
     */
    @Override
    public void complete(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }
    /**
     * 拍送订单
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);
    }

    /**
     * 接单
     * @param id
     * @return
     */
    @Override
    public void confirm(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.CONFIRMED);
        orderMapper.update(order);
    }

    /**
     * 催单
     * @param id
     * @return
     */
    @Override
    public void reminderOrder(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);
        //判断订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //判断订单状态是否为待接单
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //发送消息
        //TODO WebSocket 提醒后端!!
        Map<String, Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        log.info("催单啦！！！");
    }
}
